<?php
namespace app\admin\controller;

use app\admin\common\controller\Common;

use think\Request;
use	think\Db;
use think\facade\Session;
use think\facade\Cookie;

class Index extends Common
{
	public function login(Request $request)
	{
	    if($request->isPost()) {
            $post = $request->post();
            $post["password"] = Cookie::has("password") ? Cookie::get("password") : md5($post["password"]);
            if($user = Db::table("user")->where("username", $post["username"])->find()) {
                if($post["password"] == $user["password"]) {
                    if(isset($post["remember"])) {
                        Cookie::set("username", $user["username"], 604800);
                        Cookie::set("password", $user["password"], 604800);
                    }
                    $user["superiorname"] = $user["superior_id"] != 0 ? $user["superiorname"] = Db::table("user")->where("id", $user["superior_id"])->value("username") : "BOSS";
                    unset($user["password"]);
                    // unset($user["superior_id"]);
                    Session::set("userinfo", $user);
                    $this->success("登录成功", "index");
                }else {
                    $this->error("您输入的密码有误！");
                }
            }else {
                $this->error("该用户名不存在！");
            }
        }else {
            return view();
        }
	}
	public function logout()
	{
        Session::delete("userinfo");
        Cookie::delete("username");
        Cookie::delete("password");
		$this->success("注销成功", "login");
	}
    public function insert(Request $request)
    {
        if($request->isPost()) {
            $post = $request->post();
            if(!Db::table("user")->where("username", $post["username"])->find()) {
                $post["password"] = md5($post["password"]);
                $userId = Db::table("user")->insertGetId($post);
                if($post["superior_id"]) {
                    if($data = Db::table("rela")->where("min_id", $post["superior_id"])->where("level", "<", 7)->select()) {
                        $rela_id_list = "";
                        foreach ($data as $row) {
                            $rela_id_list = $rela_id_list . "," . $row["id"];
                            $relaData = ["path" => $row["path"] . "," . $userId, "min_id" => $userId, "level" => $row["level"] + 1];
                            Db::table("rela")->where("id", $row["id"])->update($relaData);
                        }
                        $relaData = ["max_id" => $post["superior_id"], "path" => $post["superior_id"] . "," . $userId, "min_id" => $userId];
                        $relaId = Db::table("rela")->insertGetId($relaData);
                            $rela_id_list = $rela_id_list . "," . $relaId;
                            $rela_id_list = ltrim($rela_id_list, ",");
                            $userData = ["rela_id_list" => $rela_id_list];
                            Db::table("user")->where("id", $userId)->update($userData);
                            $data = Db::table("user")->where('id', $post["superior_id"])->find();
                            $rela_id_list = $data["rela_id_list"] . "," . $relaId;
                            $userData = ["rela_id_list" => $rela_id_list];
                            Db::table("user")->where("id", $data["id"])->update($userData);
                            $this->success("新增成功！", "index");
                    }else {
						$relaIdList = Db::table("user")->where("id", $post["superior_id"])->value("rela_id_list");
						if($relaIdList) {
							$relas = Db::table("rela")->where("id", "in", $relaIdList)->where("level", "<", 7)->column("path");
							foreach($relas as $index => $rela) {
								$relas[$index] = explode(",", $rela);
							}
							$maxRela = max($relas);
							$maxRelaStr = implode(",", $maxRela);
							$strPosition = strpos($maxRelaStr, "$post[superior_id]");
							$relaStr = substr($maxRelaStr, 0, $strPosition + 2);
							$relaData = ["max_id" => $maxRela[0], "path" => $relaStr . $userId, "min_id" => $userId];
							$relaId1 = Db::table("rela")->insertGetId($relaData);
						}
						$relaData = ["max_id" => $post["superior_id"], "path" => $post["superior_id"] . "," . $userId, "min_id" => $userId];
                        $relaId2 = Db::table("rela")->insertGetId($relaData);
                        $str = $post["superior_id"] . "," . $userId;
                        $data = Db::table("user")->where("id", "in", $str)->select();
                        foreach ($data as $row) {
                            $rela_id_list = $relaIdList ? $row["rela_id_list"] . "," . $relaId1 . "," . $relaId2 : $row["rela_id_list"] . "," . $relaId2;
                            $rela_id_list = ltrim($rela_id_list, ",");
                            $userData = ["rela_id_list" => $rela_id_list];
                            Db::table("user")->where("id", $row["id"])->update($userData);
                        }
                        $this->success("新增成功！", "index");
                    }
                }else {
                    $this->success("新增成功！", "index");
                }
            }else {
                $this->error("用户名已存在！");
            }
        }else {
            $data = Db::table("user")->order("id", "desc")->select();
            $this->assign("data", $data);
            return view();
        }
    }
    public function index()
    {
        $users = Db::table("user")->order("id", "desc")->select();
        $relas = Db::table("rela")->order("id", "desc")->select();
        $revenues = Db::table("revenue")->field("revenue.*, user.username")->leftjoin("user", "revenue.user_id = user.id")->order("id", "desc")->select();
		$trees = Db::table("rela")->field("rela.*, user.username")->leftjoin("user", "rela.max_id = user.id")->where("max_id", Session::get("userinfo.id"))->select();
		$companyMoney = Db::table("company")->where("id",1)->value("money");
        $list = array();
        foreach ($trees as $index1 => $tree) {
            $list[$index1]["username"] = $tree["username"];
            $paths = explode(",", $tree["path"]);
            array_shift($paths);
            foreach ($paths as $index2 => $path) {
                $treeUser = Db::table("user")->where("id", $path)->find();
                $list[$index1]["child"][$index2]["username"] = $treeUser["username"];
                $money = Db::table("reward")->where(["user_id" => $path, "superior_id" => Session::get("userinfo.id")])->value("money");
                $money = $money ? $money : 0;
                $list[$index1]["child"][$index2]["money"] = $money;
            }
        }
        $this->assign(["users" => $users, "relas" => $relas, "revenues" => $revenues, "trees" => $list, "companymoney" => $companyMoney]);
        return view();
    }
    public function revenue(Request $request)
    {
        if($request->isPost()) {
            $post = $request->post();
            $post["months"] = strval($post["months"]);
            if(!$revenue = Db::table("revenue")->where("user_id = " . $post["user_id"] . " AND months = '" . $post["months"] . "'")->find()) {
                $data = ["user_id" => $post["user_id"], "income" => $post["income"], "months" => $post["months"]];
                Db::table("revenue")->insert($data) ? $this->success("新增成功！", "index") : $this->error("新增失败！");
            }else {
                $this->error("该用户" . $revenue["months"] . "月已录入收入！");
            }
        }else {
            $user_id = $request->param("user_id");
            $months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
            $years = [];
            foreach($months as $index => $month) {
                $years[$index] = date("Y-") . $month;
            }
            $month = date("Y-m");
            $this->assign(["years" => $years, "month" => $month, "user_id" => $user_id]);
            return view();
        }
    }
    public function calculation(Request $request)
    {
        if($request->isPost()) {
            $months = $request->post("months");
            if(!Db::table("record")->where("months", $months)->find()) {
                $usersId = Db::table("user")->where("superior_id != 0")->column("id");
                foreach ($usersId as $userId) {
                    if(!Db::table("revenue")->where(["user_id" => $userId, "months" => $months])->find()) {
                        $this->error("该月数据未全部录入！");
                        exit;
                    }
                }
            }else {
                $this->error("本月已计算！");
                exit;
            }
            $commission = [0.50, 0.20, 0.30];
            $superiorCommission = [0.09, 0.06, 0.05, 0.04, 0.03, 0.02, 0.01];
            $datas = Db::table("revenue")->where("months", $months)->order("id", "desc")->select();
            $income = null;
            foreach ($datas as $data) {
                $income = $data["income"];
                $money = [];
                foreach ($commission as $index => $item) {
                    $money[$index] = $data["income"] * $commission[$index];
                }
                $user = Db::table("user")->where("id", $data["user_id"])->find();
                $reve = Db::table("revenue")->where(["user_id" => $data["user_id"], "months" => $months])->find();
                $reve ? Db::table("revenue")->where(["user_id" => $user["id"], "months" => $months])->update(["wages" => $money[0] + $reve["wages"]]) : Db::table("revenue")->where("user_id", $user["id"])->update(["wages" => $money[0]]);
                $userReward = Db::table("reward")->where(["user_id" => $user["id"], "superior_id" => $user["id"], "months" => $months])->find();
                !$userReward ? Db::table("reward")->insert(["user_id" => $user["id"], "money" => $money[0], "superior_id" => $user["id"], "months" => $months]) : "";
                $companyMoney = Db::table("company")->where("id", 1)->value("money");
                Db::table("company")->where("id", 1)->update(["money" => $money[1] + $companyMoney]);
                $rela_id_lists = explode(",", $user["rela_id_list"]);
                $paths = [];
                foreach ($rela_id_lists as $index => $rela_id_list) {
                    $rela = Db::table("rela")->where("id", $rela_id_list)->find();
                    $strPosition = strpos($rela["path"], "$user[id]");	//	获取关键字出现位置
                    $pathStr = substr($rela["path"], 0, $strPosition);	//	截取字符串下标0开始到关键字出现位置
                    $paths[$index] = explode(",", $pathStr);	//	以，分割字符串为数组
                    $paths[$index] = array_reverse($paths[$index]);	//	翻转数组
                    array_shift($paths[$index]);	//	删除头部数组
                }
                $maxPaths = max($paths);	//	获取二维数组中长度最长的数组
                $maxPathsLength = count($maxPaths);
                $superiorMoney = [];
                $rewardMoney = 0;
                foreach ($maxPaths as $index => $maxPath) {
                    $superiorMoney[$index] = $income * $superiorCommission[$index];
                    if($revenue = Db::table("revenue")->where(["user_id" => $maxPath, "months" => $months])->find()) {
                        $revenueData = ["wages" => $revenue["wages"] + $superiorMoney[$index]];
                        Db::table("revenue")->where("id", $revenue["id"])->update($revenueData);
                        $maxPathsLength != 7 ? $rewardMoney += $superiorMoney[$index] : "";
                    }else {
                        $revenueData = ["user_id" => $maxPath, "wages" => $superiorMoney[$index], "months" => $months];
                        Db::table("revenue")->insert($revenueData);
                        $maxPathsLength != 7 ? $rewardMoney += $superiorMoney[$index] : "";
                    }
                    if($reward = Db::table("reward")->where(["user_id" => $user["id"], "superior_id" => $maxPath, "months" => $months])->find()) {
                        Db::table("reward")->where("id", $reward["id"])->update(["money" => $reward["money"] + $superiorMoney[$index]]);
                    }else {
                        $rewardData = ["user_id" => $user["id"], "money" => $superiorMoney[$index], "superior_id" => $maxPath, "months" => $months];
                        Db::table("reward")->insert($rewardData);
                    }
                }
                if($maxPathsLength != 7) {
                    $surplusMoney = $money[2] - $rewardMoney;
                    $companyMoney = Db::table("company")->where("id", 1)->value("money");
                    $companyData = ["money" => $companyMoney + $surplusMoney];
                    Db::table("company")->where("id", 1)->update($companyData);
                }
            }
            Db::table("record")->insert(["months" => $months]);
            $this->success("计算成功！", "index");
        }else {
            if($data = Db::table("revenue")->group("months")->column("months")) {
                $this->assign(["data" => $data, "months" => date("Ym")]);
                return view();
            }else {
                $this->error("暂无数据！");
            }
        }
	}
	public function emptytable()
	{
        Session::delete("userinfo");
        Cookie::delete("username");
        Cookie::delete("password");
		Db::execute("TRUNCATE TABLE user");
		Db::execute("TRUNCATE TABLE rela");
        Db::execute("TRUNCATE TABLE revenue");
        Db::execute("TRUNCATE TABLE reward");
        Db::execute("TRUNCATE TABLE record");
        Db::table("company")->where("id", 1)->update(["money" => 0]);
        Db::table("user")->insert(["username" => "admin", "password" => md5("admin"), "superior_id" => 0]);
		$this->success("清空数据表成功", "index");
	}
	public function emptyrevenue()
	{
		Db::execute("TRUNCATE TABLE revenue");
		Db::execute("TRUNCATE TABLE reward");
        Db::execute("TRUNCATE TABLE record");
		Db::table("company")->where("id", 1)->update(["money" => 0]);
		$this->success("清空数据表成功", "index");
	}
}
